﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Middleware;
using System.Text;
using System.Threading.Tasks;
using TESTCommons.HttpHelper;
using TESTCommons.JsonHelper;
using TestManage.Infrastructure.LogWrite;
using TestModel.SysManage;
using TestService.SysManage;

namespace TestManage.Infrastructure.Extensions
{
    /// <summary>
    /// Represents extensions of IApplicationBuilder
    /// </summary>
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// Configure the application HTTP request pipeline
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void ConfigureRequestPipeline(this IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //env.AddUserSecrets();
            }
            else
            {
                //app.UseDeveloperExceptionPage();
                //app.UseExceptionHandler("/Home/Error");
                app.UseExceptionHandler(builder => builder.Run(async context => await LogHelper.ErrorEvent(context)));
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //app.UseOcelot().Wait();//设置所有的Ocelot中间件


            //身份验证
            app.UseAuthentication();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            //session 注册
            app.UseSession();
            //use request localization
            app.UseRequestLocalization();
            //将 对象 IHttpContextAccessor 注入 HttpContextHelper 静态对象中
            HttpContextHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());

            //跨域
            //app.UseCors(builder =>
            //{
            //    builder.WithOrigins("http://localhost:12406/")
            //        .AllowAnyHeader()
            //        .WithMethods("GET", "POST")
            //        .AllowCredentials();
            //});
            app.UseCors("_myAllowSpecificOrigins");
            //app.UseSignalR(routes =>
            //{
            //    routes.MapHub<ChatHub>("/chatHub");
            //});


            app.UseMvc(routes =>
            {
                routes.MapRoute( 
                    name: "areas",
                    template: "{area:exists}/{controller=Login}/{action=Index}/{id?}");

                routes.MapRoute( 
                    name: "default",
                    template: "{controller=Login}/{action=Index}/{id?}");
            });
        }
    }
}
